import React, {Component} from 'react'
import {Card, Form, Icon, Input, Cascader, Upload, Button, message} from "antd";
import LinkButon from '../../components/link-button'
import {reqCategoryAll, reqCategory} from '../../api'
import PicturesWall from './pictures-wall';
import RichTextEditor from './rich-text-editor'

const {Item} = Form
const {TextArea} = Input


/**
 *product的添加和更新的子路由组件
 */
class ProductAddUpdate extends Component {

    state = {
        options: [],
    };

    constructor(props) {
        super(props)
        //创建用来保存ref的标签对象的容器
        this.pw = React.createRef()
        this.editor = React.createRef()
    }


    initOptions = async (categorys) => {
        console.log('categorys')
        console.log(categorys)
        //根据categorys生产options数组
        const options = categorys.map(c => ({
            value: c.id,
            label: c.username,
            //不是叶子
            isLeaf: false,
        }))
        //如果是一个二级分类商品的更新
        const {isUpdate, product} = this
        const {id, deleted} = product
        if (isUpdate && deleted == '0') {
            //获取对应的二级分类列表
            const subCategorys = await this.getCategorys(deleted)
            //生成二级列表的options
            const childOptions = subCategorys.map(c => ({
                value: c.id,
                label: c.username,
                //不是叶子
                isLeaf: false,
            }))
            //找到当前商品对应的options
            const targetOption = options.find(option => option.value === deleted)
            //关联对应的一级option上
            targetOption.children = childOptions
        }
        //更新options状态
        this.setState({
            options: [...options]
        })
    }

    /**
     * 获取一级二级分类列表，并显示
     * async函数返回值是一个新的promise对象，promise的结果和值由async的结果来决定
     */
    getCategorys = async (parentId) => {
        const result = await reqCategoryAll(parentId)
        if (result.code === 200) {
            const categorys = result.data
            if (parentId === '0') {
                this.initOptions(categorys)
            } else {
                //返回二级列表
                return categorys
            }
        }
    }

    /**
     * 验证价格
     */
    validatePrice = (rule, value, callback) => {
        if (value * 1 > 0) {
            callback() //验证通过
        }
        callback('价格必须大于一')
    }

    loadData = async selectedOptions => {
        // 得到选择的option对象
        const targetOption = selectedOptions[0];
        // 显示loading
        targetOption.loading = true

        //根据选中的分类，请求获取二级分类列表
        const subCategorys = await this.getCategorys(targetOption.value)
        // 显示loading
        targetOption.loading = false
        if (subCategorys && subCategorys.length > 0) {
            //生成二级列表的options
            const childOptions = subCategorys.map(c => ({
                value: c.id,
                label: c.username,
                isLeaf: true,
            }))
            targetOption.children = childOptions
        } else {//当前选择的分类没有二级分类
            targetOption.isLeaf = true
        }
        this.setState({
            options: [...this.state.options],
        })
    }


    submit = () => {
        //进行表单验证，通过了，从发生请求
        this.props.form.validateFields((error, values) => {
            if (!error) {
                //1.收集数据
                const imgs = this.pw.current.getImgs()
                const edtail = this.editor.current.getDetail()
                console.log(values)
                console.log(imgs)
                console.log(edtail)
                //2.调用接口请求函数去添加

                //3.根据结果



                alert('fasong')
            }
        })
    }

    componentWillMount() {
        //取出携带的state    如果是添加
        const product = this.props.location.state
        //保存是否更新的标识
        this.isUpdate = !!product
        this.product = product || {}
    }

    componentDidMount() {
        this.getCategorys('0')
    }

    render() {
        const {isUpdate, product} = this
        const {classify, price, imgs} = product
        const categoryIds = []

        if (isUpdate) {
            //商品是一个一级分类的商品
            if (classify === '0') {
                categoryIds.push(classify)
            } else {
                //商品是一个二级分类id
                categoryIds.push(classify)
                categoryIds.push(price)
            }
        }
        //指定Item布局的配置对象
        const formItemLayout = {
            //左侧label占6格
            labelCol: {span: 2},
            wrapperCol: {span: 8}
        }

        const title = (
            <span>
                <LinkButon>
                    <Icon type='arrow-left'
                          onClick={() => this.props.history.goBack()}></Icon>

                </LinkButon>
                <span>添加商品</span>
            </span>
        )

        const {getFieldDecorator} = this.props.form

        return (
            <Card title={title}>
                <Form {...formItemLayout}>
                    <Item label="商品名称">
                        {
                            getFieldDecorator('productname', {
                                initialValue: product.productname,
                                rules: [
                                    {
                                        required: true, message: '必须输入商品名称'
                                    }
                                ]
                            })(<Input placeholder='请输入商品名称'/>)
                        }
                    </Item>

                    <Item label="商品描述">
                        {
                            getFieldDecorator('desc1', {
                                initialValue: product.desc1,
                                rules: [
                                    {
                                        required: true, message: '必须输入商品描述'
                                    }
                                ]
                            })(<TextArea placeholder='请输入商品描述' autosize/>)
                        }
                    </Item>

                    <Item label="商品价格">
                        {
                            getFieldDecorator('price', {
                                initialValue: product.price,
                                rules: [
                                    {
                                        required: true, message: '必须输入商品价格'
                                    },
                                    {
                                        validator: this.validatePrice
                                    }
                                ]
                            })(<Input type='number' placeholder='请输入商品价格' addonAfter='元'/>)
                        }
                    </Item>
                    <Item label="商品分类">
                        {
                            getFieldDecorator('categoryIds', {
                                initialValue: categoryIds,
                                rules: [
                                    {required: true, message: '必须指定商品分类'},
                                ]
                            })(
                                <Cascader
                                    placeholder='请指定商品分类'
                                    options={this.state.options}  /*需要显示的列表数据数组*/
                                    loadData={this.loadData} /*当选择某个列表项, 加载下一级列表的监听回调*/
                                />
                            )
                        }
                    </Item>
                    <Item label="商品图片">
                        <PicturesWall ref={this.pw} imgs={imgs}/>
                    </Item>
                    <Item label="商品详情" labelCol={{span: 2}} wrapperCol={{span: 20}}>
                        <RichTextEditor ref={this.editor}/>
                    </Item>
                    <Item>
                        <Button type='primary' onClick={this.submit}>提交</Button>
                    </Item>
                </Form>
            </Card>
        )
    }
}

export default Form.create()(ProductAddUpdate)

/**
 * 1.子组件调用父组件的方法，将父组件的方法以函数属性的形式传递给子组件，子组件就可以调用
 * 2.父组件调用子组件的方法:在父组件中通过ref得到子组件标签对象（也就是组件对象），调用其方法
 */